package com.dinglian.ots.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.dinglian.ots.common.EncryptHelper;
import com.dinglian.ots.common.ToolUtils;
import com.dinglian.ots.common.model.Constant;
import com.dinglian.ots.dao.mapper.*;
import com.dinglian.ots.dao.model.*;
import com.dinglian.ots.exception.GlobalException;
import com.dinglian.ots.redis.RedisService;
import com.dinglian.ots.result.CodeMsg;
import com.dinglian.ots.service.BuyerService;
import com.dinglian.ots.service.CommonService;
import com.dinglian.ots.shiro.MyShiroToken;
import com.dinglian.ots.vo.address.AddAddressVo;
import com.dinglian.ots.vo.address.AddressListVo;
import com.dinglian.ots.vo.address.UpdateAddressVo;
import com.dinglian.ots.vo.brand.AgreeVo;
import com.dinglian.ots.vo.buyer.*;
import com.dinglian.ots.vo.collection.CollectionVo;
import com.dinglian.ots.vo.user.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author wangbo
 */
@Service
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private CommonService commonService;

    @Value("${pic.path}")
    private String path;

    @Value("${pic.url}")
    private String url;

    @Value("${address}")
    private String address;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ParamRelationMapper paramRelationMapper;

    @Autowired
    private CategoryRelationMapper categoryRelationMapper;

    @Autowired
    private UserRelationMapper userRelationMapper;

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User saveBuyer(BuyerVo buyerVo) {
        //验证短信验证码
        String mobile = buyerVo.getMobile();
        String code = buyerVo.getCode();
        commonService.checkCode(mobile, code);

        UserExample userExample = new UserExample();
        userExample.or().andUsernameEqualTo(mobile);
        List<User> users = userMapper.selectByExample(userExample);
        if (!users.isEmpty()) {
            throw new GlobalException(CodeMsg.USERNAME_IS_EXIST);
        }

        String name = buyerVo.getName();
        String password = buyerVo.getPassword();
        //保存用户表 获取userId
        User user = new User();
        user.setName(name);
        user.setUsername(mobile);
        user.setAvailable(true);
        user.setLevel(0);
        //添加密码 加密待定！
//        password = EncryptHelper.SHA1(password);
        user.setPassword(password);
        //添加角色
        user.setRoleId(Constant.BUYER_ROLE);

        userMapper.insertSelective(user);

        int userId = user.getId();

        Integer priceUpperLimit = buyerVo.getPriceUpperLimit();
        Integer priceDownLimit = buyerVo.getPriceDownLimit();
        String introduction = buyerVo.getIntroduction();
        introduction = ToolUtils.urlDecoder(introduction);
        String email = buyerVo.getEmail();
        String company = buyerVo.getCompany();


        //保存店铺信息
        Store store = new Store();
        String addressList = buyerVo.getAddressList();
        JSONArray jsonArray = JSONArray.parseArray(addressList);
        if (!jsonArray.isEmpty()) {
            if (jsonArray.size() == 0) {
                store.setType("连锁店");
            } else {
                store.setType("买手店");
            }
        }
        //解析图片 上传

        MultipartFile[] pictures = buyerVo.getPictures();
        JSONArray detailsPic = new JSONArray();
        for (int i = 0; i < pictures.length; i++) {
            String fileId = ToolUtils.uploadPicture(path, name, Constant.BUYER_DETAIL, pictures[i]);
            detailsPic.add(url + fileId);
        }

        MultipartFile businessLicense = buyerVo.getBusinessLicense();
        String businessFileId = ToolUtils.uploadPicture(path, name, Constant.BUYER_BUSINESS, businessLicense);


        MultipartFile historyTransaction = buyerVo.getHistoryTransaction();
        if (historyTransaction != null) {
            String historyFileId = ToolUtils.uploadFile(path, name, Constant.BUYER_HISTORY, historyTransaction);
            store.setHistoryTransaction(url + historyFileId);
        }

        store.setBusinessLicense(url + businessFileId);
        store.setPriceUpperLimit(priceUpperLimit);
        store.setPriceDownLimit(priceDownLimit);
        store.setPictureUrls(detailsPic.toJSONString());
        store.setName(name);
        store.setMobile(mobile);
        store.setIntroduction(introduction);
        store.setEmail(email);
        store.setCompany(company);
        //先改为已审核
        store.setStatus(Constant.SUBMITTED);
//        store.setStatus(Constant.UNAUDITED);
        storeMapper.insertSelective(store);

        Integer storeId = store.getId();

        //保存品类/风格 关系
        String styleIds = buyerVo.getStyleIds();
        String categoryIds = buyerVo.getCategoryIds();
        String[] styleList = styleIds.split(",");
        for (int i = 0; i < styleList.length; i++) {
            String styleId = styleList[i];
            ParamRelation paramRelation = new ParamRelation();
            paramRelation.setStyleId(Integer.valueOf(styleId));
            paramRelation.setTargetId(storeId);
            //1店铺 2品牌 3商品
            paramRelation.setType(Constant.TYPE_STORE);
            paramRelationMapper.insertSelective(paramRelation);
        }

        String[] categoryList = categoryIds.split(",");
        for (int i = 0; i < categoryList.length; i++) {
            String categoryId = categoryList[i];
            CategoryRelation categoryRelation = new CategoryRelation();
            categoryRelation.setCategoryId(Integer.valueOf(categoryId));
            categoryRelation.setTargetId(storeId);
            //1店铺 2品牌 3商品
            categoryRelation.setType(Constant.TYPE_STORE);
            categoryRelationMapper.insertSelective(categoryRelation);
        }

        //保存关联表
        UserRelation userRelation = new UserRelation();
        userRelation.setTargetId(storeId);
        userRelation.setUserId(userId);
        userRelation.setType(Constant.TYPE_STORE);
        userRelationMapper.insertSelective(userRelation);


        //保存地址
        for (int i = 0; i < jsonArray.size(); i++) {
            String address = (String) jsonArray.get(i);
            Address ad = new Address();
            ad.setAddress(address);
            ad.setMobile(mobile);
            ad.setUserId(userId);
            ad.setName(name);
            addressMapper.insertSelective(ad);
        }
        return user;
    }

    @Override
    public BuyerInfoVo getBuyerInfo(Integer storeId) {
        System.out.println("storeId"+storeId);
        BuyerInfoVo buyerInfoVo = storeMapper.getBuyerInfo(storeId);
        String styleIdStr = buyerInfoVo.getStyleIdStr();
        if (!StrUtil.isBlank(styleIdStr)){
            List<Integer> styleIds = new ArrayList<>();
            String[] styleSplit = styleIdStr.split(",");
            for (int i = 0; i <styleSplit.length ; i++) {
                styleIds.add(Integer.valueOf(styleSplit[i]));
            }
            buyerInfoVo.setStyleIds(styleIds);
        }

        String categoryStr = buyerInfoVo.getCategoryIdStr();
        if (!StrUtil.isBlank(categoryStr)){
            List<Integer> categoryIds = new ArrayList<>();
            String[] categorySplit = categoryStr.split(",");
            for (int i = 0; i <categorySplit.length ; i++) {
                categoryIds.add(Integer.valueOf(categorySplit[i]));
            }
            buyerInfoVo.setCategoryIds(categoryIds);
        }
        String pictureStr = buyerInfoVo.getPictureStr();
        if (!StrUtil.isBlank(pictureStr)){
            buyerInfoVo.setPictures(JSONArray.parseArray(pictureStr));
        }

        return buyerInfoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBuyerInfo(UpdateBuyerVo buyerVo) {

        Integer storeId = buyerVo.getStoreId();
        Store store = storeMapper.selectByPrimaryKey(storeId);
        String fileName = store.getName();

        Integer priceUpperLimit = buyerVo.getPriceUpperLimit();
        Integer priceDownLimit = buyerVo.getPriceDownLimit();
        String introduction = buyerVo.getIntroduction();
        introduction = ToolUtils.urlDecoder(introduction);
        String company = buyerVo.getCompany();

        //解析图片 上传

        MultipartFile[] pictures = buyerVo.getPictures();
        if (pictures != null) {
            JSONArray detailsPic = new JSONArray();
            for (int i = 0; i < pictures.length; i++) {
                String fileId = ToolUtils.uploadPicture(path, fileName, Constant.BUYER_DETAIL, pictures[i]);
                detailsPic.add(url + fileId);
            }
            store.setPictureUrls(detailsPic.toJSONString());
        }


        MultipartFile businessLicense = buyerVo.getBusinessLicense();
        if (businessLicense != null) {
            String businessFileId = ToolUtils.uploadPicture(path, fileName, Constant.BUYER_BUSINESS, businessLicense);
            store.setBusinessLicense(url + businessFileId);
        }


        MultipartFile historyTransaction = buyerVo.getHistoryTransaction();
        if (historyTransaction != null) {
            String historyFileId = ToolUtils.uploadFile(path, fileName, Constant.BUYER_HISTORY, historyTransaction);
            store.setHistoryTransaction(url + historyFileId);
        }


        store.setPriceUpperLimit(priceUpperLimit);
        store.setPriceDownLimit(priceDownLimit);

        store.setName(buyerVo.getName());
        store.setIntroduction(introduction);
        store.setCompany(company);
        storeMapper.updateByPrimaryKeySelective(store);


        String categoryIds = buyerVo.getCategoryIds();
        if (!StrUtil.isBlank(categoryIds)) {

            CategoryRelationExample categoryRelationExample = new CategoryRelationExample();
            categoryRelationExample.or().andTypeEqualTo(Constant.TYPE_STORE).andTargetIdEqualTo(storeId);
            categoryRelationMapper.deleteByExample(categoryRelationExample);

            String[] categoryList = categoryIds.split(",");
            for (int i = 0; i < categoryList.length; i++) {
                String categoryId = categoryList[i];
                CategoryRelation categoryRelation = new CategoryRelation();
                categoryRelation.setCategoryId(Integer.valueOf(categoryId));
                categoryRelation.setTargetId(storeId);
                //1店铺 2品牌 3商品
                categoryRelation.setType(Constant.TYPE_STORE);
                categoryRelationMapper.insertSelective(categoryRelation);
            }
        }


        String styleIds = buyerVo.getStyleIds();
        if (!StrUtil.isBlank(styleIds)) {
            ParamRelationExample paramRelationExample = new ParamRelationExample();
            paramRelationExample.or().andTypeEqualTo(Constant.TYPE_STORE).andTargetIdEqualTo(storeId);
            paramRelationMapper.deleteByExample(paramRelationExample);

            String[] styleList = styleIds.split(",");
            for (int i = 0; i < styleList.length; i++) {
                String styleId = styleList[i];
                ParamRelation paramRelation = new ParamRelation();
                paramRelation.setStyleId(Integer.valueOf(styleId));
                paramRelation.setTargetId(storeId);
                //1店铺 2品牌 3商品
                paramRelation.setType(Constant.TYPE_STORE);
                paramRelationMapper.insertSelective(paramRelation);
            }
        }

    }

    @Override
    public void buyerCollect(CollectionVo collectionVo) {
        if (collectionVo.isCancel()) {
            FollowExample followExample = new FollowExample();
            followExample.or().andUserIdEqualTo(collectionVo.getUserId()).andTargetIdEqualTo(collectionVo.getTargetId()).andTypeEqualTo(collectionVo.getType());
            followMapper.deleteByExample(followExample);
        } else {
            Follow follow = new Follow();
            follow.setUserId(collectionVo.getUserId());
            follow.setTargetId(collectionVo.getTargetId());
            follow.setType(collectionVo.getType());
            followMapper.insertSelective(follow);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAddress(AddAddressVo addressVo) {
        Integer prime = addressVo.getPrime();
        Integer userId = addressVo.getUserId();
        Address address = new Address();
        if (prime == 1) {
            address.setPrime(0);
            AddressExample addressExample = new AddressExample();
            addressExample.or().andUserIdEqualTo(userId);
            addressMapper.updateByExampleSelective(address, addressExample);
        }
        address.setPrime(prime);
        address.setAddress(addressVo.getAddress());
        address.setMobile(addressVo.getMobile());
        address.setName(addressVo.getName());
        address.setUserId(userId);
        addressMapper.insertSelective(address);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAddress(UpdateAddressVo addressVo) {
        Integer prime = addressVo.getPrime();
        Integer userId = addressVo.getUserId();
        Address address = new Address();
        if (prime == 1) {
            address.setPrime(0);
            AddressExample addressExample = new AddressExample();
            addressExample.or().andUserIdEqualTo(userId);
            addressMapper.updateByExampleSelective(address, addressExample);
        }
        address.setId(addressVo.getAddressId());
        address.setPrime(prime);
        address.setAddress(addressVo.getAddress());
        address.setMobile(addressVo.getMobile());
        address.setName(addressVo.getName());
        addressMapper.updateByPrimaryKeySelective(address);
    }

    @Override
    public void deleteAddress(Integer addressId) {
        addressMapper.deleteByPrimaryKey(addressId);
    }

    @Override
    public List<AddressListVo> getAddressList(Integer userId) {
        return addressMapper.getAddressList(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyForIntention(ApplicationVo applicationVo) {
        Integer buyerId = applicationVo.getUserId();
        Integer brandId = applicationVo.getBrandId();
        RelationExample relationExample = new RelationExample();
        relationExample.or().andBrandIdEqualTo(brandId).andBuyerIdEqualTo(buyerId);
        List<Relation> relations = relationMapper.selectByExample(relationExample);

        //查询brandId所对应的userId
        Integer userId = userMapper.selectUserIdByTargetId(applicationVo.getBrandId(), Constant.TYPE_BRAND);
        if (userId == null) {
            throw new GlobalException(CodeMsg.USER_ID_NOT_FOUND);
        }
        Integer relationId = null;
        if (!relations.isEmpty()) {
            Relation relation = relations.get(0);
            relationId = relation.getId();
        } else {
            //保存关联关系表
            Relation relation = new Relation();
            relation.setBuyerId(buyerId);
            relation.setBrandId(applicationVo.getBrandId());
            relation.setIsPass(false);
            relation.setType(2);
            relationMapper.insertSelective(relation);
            relationId = relation.getId();
        }

        BuyerMsgVo buyerMsgVo = storeMapper.getStoreByBuyerId(buyerId);

        //组成文案
        //保存站内信
        Message message = new Message();
        message.setUserId(userId);
        message.setTitle("您有新的买手意向申请");


        StringBuilder sb = new StringBuilder();
        sb.append("<a href=\"" + address + "#/invite/inviteManage\">☞点击查看</a>");
        message.setMessage(sb.toString());
        messageMapper.insertSelective(message);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agreeInvitation(AgreeVo agreeVo) {
        Integer relationId = agreeVo.getRelationId();
        boolean isPass = agreeVo.isPass();
        Relation relation = relationMapper.selectByPrimaryKey(relationId);
        Integer buyerId = relation.getBuyerId();
        BuyerMsgVo buyerMsgVo = storeMapper.getStoreByBuyerId(buyerId);
        Integer userId = userMapper.selectUserIdByTargetId(relation.getBrandId(), Constant.TYPE_BRAND);
        Message message = new Message();
        message.setUserId(userId);

        //查询子品牌
        Integer brandId = relation.getBrandId();
        List<Map> childBrand = brandMapper.getChildBrand(brandId);

        if (isPass) {
            relation.setIsPass(true);
            relation.setId(relationId);
            relation.setType(3);
            relation.setLastUpdateTime(DateUtil.date());
            relationMapper.updateByPrimaryKeySelective(relation);
            //成功
            message.setTitle(buyerMsgVo.getStoreName() + "已接受了您的邀请");
            message.setMessage(buyerMsgVo.getStoreName() + "已接受了您的邀请");
        } else {
            relation.setIsPass(false);
            relation.setId(relationId);
            relation.setType(4);
            relation.setLastUpdateTime(DateUtil.date());
            relationMapper.updateByPrimaryKeySelective(relation);
            //失败
            message.setTitle(buyerMsgVo.getStoreName() + "拒绝了您的邀请");
            message.setMessage(buyerMsgVo.getStoreName() + "拒绝了您的邀请");
        }

        if (!childBrand.isEmpty()){
            for (int i = 0; i < childBrand.size(); i++) {
                Map map = childBrand.get(i);
                Integer id = (Integer) map.get("id");
                relation.setBrandId(id);
                relationMapper.insertSelective(relation);
            }
        }

        messageMapper.insertSelective(message);
    }

    @Override
    public PageInfo<SearchBuyerVo> searchBuyer(Integer brandId, Integer provinceId, Integer cityId, String styleIds, String type, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<String> styleStr = new ArrayList<>();
        if (styleIds != null) {
            String[] split = styleIds.split(",");
            styleStr = Arrays.asList(split);
        }
        List<SearchBuyerVo> searchBuyerVos = relationMapper.searchBuyer(brandId, provinceId, cityId, styleStr, type);
        return new PageInfo<>(searchBuyerVos);
    }
}
